import { ceil } from 'lodash-es'

// beta
export default defineComponent({
  props: {
    data: {
      type: Array,
      default: () => []
    },
    columns: {
      type: Array,
      default: () => []
    },
    //是否显示筛选功能
    showSift: {
      type: Boolean,
      default: true
    },
    // page
    fetchData: {
      type: Function
    },
    isPage: {
      type: Boolean,
      default: true
    },
    selectAll: {
      type: Function
    },
    autoRequest: {
      type: Boolean,
      default: true
    },
    checkBackSelect: {
      type: Array,
      default: () => []
    }
  },
  // emits:{
  //   "selection-change":null
  // },
  setup(props, { expose, attrs, emit }) {
    // page
    const checkedListInfo = toRef(props.checkBackSelect)
    const page = ref(1)
    const pageSize = ref(10)
    const count = ref(0)
    const loading = ref(false)
    const dataAsync = ref([])
    const tableRef = ref()
    const checkedList = ref({})
    const refresh = ref(true)
    const pageChecked = ref({})
    const isAutoSelect = ref(false)
    let siftStore = ref([])
    const modifiedValue = ref(1)
    const inputValue = ref(1)
    const _columns = computed(() => {
      return props.columns
    })
    const siftCheckedList = ref([])
    const isAsync = computed(() => typeof props.fetchData === 'function')
    const addSift = () => {
      _columns.value[_columns.value.length - 1].renderHeader ||
        (_columns.value[_columns.value.length - 1].renderHeader = ({ row }) => {
          return (
            <>
              <el-popover
                placement="bottom"
                width="40"
                trigger="click"
                onBefore-enter={(_) => {
                  siftStore.value = siftCheckedList.value
                }}
                v-slots={{
                  reference: () => (
                    <span>
                      {_columns.value[_columns.value.length - 1].label ?? ''}
                      <Icon
                        size={14}
                        class="m-l-10px vertical-middle"
                        icon="svg-icon:operation"
                      ></Icon>
                    </span>
                  )
                }}
              >
                <el-checkbox-group
                  v-model={siftStore.value}
                  onChange={(val) => {}}
                  style={{ maxHeight: '300px', overflow: 'auto' }}
                >
                  {props.columns.map((item, idx) => {
                    return !item.type && idx != props.columns.length - 1 ? (
                      <el-checkbox
                        style={{ display: 'block' }}
                        value={item.label}
                        label={item.label}
                      ></el-checkbox>
                    ) : (
                      ''
                    )
                  })}
                </el-checkbox-group>
                <div class="flex">
                  <el-button
                    class="m-l-auto mt2"
                    type="primary"
                    size="small"
                    onClick={(_) => {
                      refresh.value = false
                      _columns.value.map((item, idx) => {
                        if (!item.type && idx != _columns.value.length - 1) {
                          item.hide = siftStore.value.indexOf(item.label) < 0
                        } else {
                          return item
                        }
                      })
                      siftCheckedList.value = siftStore.value
                      nextTick(() => {
                        refresh.value = true
                      })
                    }}
                  >
                    确认
                  </el-button>
                </div>
              </el-popover>
            </>
          )
        })
    }
    watchEffect(() => {
      _columns.value
      siftCheckedList.value.length < 1 &&
        (siftCheckedList.value = _columns.value.map((item) => item.label).filter((item) => item))
      props.showSift &&
        _columns.value.length &&
        !props.columns[props.columns.length - 1].label.includes('操作') &&
        addSift()
    })
    watchEffect(() => {
      props.columns
      siftCheckedList.value = props.columns.map((item) => item.label).filter((item) => item)
      console.log(props.columns[props.columns.length - 1])

      props.showSift &&
        props.columns.length &&
        !props.columns[props.columns.length - 1].label.includes('操作') &&
        addSift()
    })
    const rows = computed(() => {
      if (isAsync.value) {
        return dataAsync.value
      }
      return props.data
    })
    async function _ignorePageSelect(checked) {
      isAutoSelect.value = checked
      dataAsync.value?.length &&
        dataAsync.value.map((item) => {
          tableRef.value.toggleRowSelection(item, checked)
        })
    }
    async function _checkBackSelect(list, checked) {
      list.length != 0 &&
        list.map((item) => {
          tableRef.value.toggleRowSelection(item, true)
        })
    }
    async function _fetchData() {
      loading.value = true
      if (typeof props.fetchData === 'function') {
        const res = await props
          .fetchData({
            page: page.value,
            pageSize: pageSize.value
          })
          .catch(() => {})
        typeof res?.count !== 'undefined' && (count.value = res.count)
        typeof res?.page !== 'undefined' && (page.value = res.page)
        dataAsync.value = res?.rows || res?.data
        nextTick(() => {
          isAutoSelect.value
            ? _ignorePageSelect(isAutoSelect.value)
            : pageChecked.value[page.value]?.length &&
              dataAsync.value.map((item) => {
                if (pageChecked.value[page.value].find((v) => v.id == item.id)) {
                  tableRef.value.toggleRowSelection(item, true)
                }
              })
          checkedList.value.length && emit('selectionChange', checkedList.value)
        })
      }
      loading.value = false
    }
    function _selectAll(list) {
      if (typeof props.selectAll === 'function') {
        props.selectAll(list)
      }
      _onSelectionChange(list)
    }
    async function sizeChange(val) {
      page.value = 1
      pageSize.value = val
      _fetchData()
    }

    async function currentChange(val) {
      if (inputValue.value == '') {
        page.value = modifiedValue.value
        inputValue.value = modifiedValue.value
      } else {
        page.value = val
        _fetchData()
      }
    }
    const _pageReload = () => {
      currentChange(1)
    }
    function resetPage() {
      page.value = 1
      count.value = 0
    }
    function exposeFetchData() {
      checkedList.value = []
      pageChecked.value = {}
      _fetchData()
    }
    const handleInput = (val) => {
      if (!/[1-9]*/.test(val.target.value) || val.target.value < 1) {
        modifiedValue.value = page.value
        inputValue.value = ''
      } else {
        inputValue.value = val.data
      }
    }

    expose({
      fetchData: exposeFetchData,
      elTable: tableRef,
      selectAll: _selectAll,
      ignorePageSelect: _ignorePageSelect,
      resetPage,
      pageReload: _pageReload,
      currentPageReload: _fetchData
    })
    onMounted(() => {
      if (props.autoRequest) {
        _fetchData()
      }
      if (checkedListInfo.value?.length > 0) {
        _checkBackSelect(checkedListInfo.value, true)
      }
    })
    function _onSelectionChange(list) {
      pageChecked.value[page.value] = list
      checkedList.value = []
      for (var i in pageChecked.value) {
        checkedList.value.push(...pageChecked.value[i])
      }
      emit('selectionChange', checkedList.value)
    }

    function renderColumns() {
      return _columns.value
        .filter((item) => !item.hide)
        .map((column, index) => {
          const { render, hide, ...columnAttrs } = column

          if (typeof render === 'function') {
            const _render = (scope) => {
              if (columnAttrs.prop) {
                return render(scope.row[columnAttrs.prop], scope)
              }
              return render(scope)
            }

            return (
              <el-table-column
                key={index}
                {...columnAttrs}
                show-overflow-tooltip={column.isShowOverflowTooltip == 'false' ? false : true}
              >
                {_render}
              </el-table-column>
            )
          }
          const _renderPlaceholder = (scope) => {
            let collVal = scope.row[columnAttrs.prop]
            return collVal == '' ? '--' : collVal
          }
          return (
            <el-table-column key={index} {...columnAttrs} show-overflow-tooltip>
              {_renderPlaceholder}
            </el-table-column>
          )
        })
    }

    return () => (
      <>
        <el-table
          v-loading={loading.value}
          data={rows.value}
          {...attrs}
          onSelect={(list, row) => _onSelectionChange(list, row)}
          onSelectAll={(list) => _selectAll(list)}
          ref={tableRef}
          border
          row-key={(row) => {
            if (row?.metaInfoName) {
              return row.metaInfoName
            } else {
              return row.id
            }
          }}
        >
          {refresh.value && renderColumns()}
        </el-table>
        {props.isPage ? (
          <el-pagination
            current-page={page.value}
            page-size={pageSize.value}
            {...{
              'onUpdate:currentPage': currentChange,
              'onUpdate:pageSize': sizeChange
            }}
            total={+count.value}
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-16px justify-end"
            onInput={handleInput}
          />
        ) : (
          ''
        )}
      </>
    )
  }
})
